package cn.lijiancn01.demo.system.codegen;

import com.google.common.collect.HashBasedTable;
import com.mybatisflex.codegen.config.GlobalConfig;
import com.mybatisflex.codegen.entity.Table;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.Setter;
import lombok.experimental.Accessors;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Marker;
import org.slf4j.MarkerFactory;

import javax.sql.DataSource;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 代码生成器（支持预览和生成文件）
 *
 * @see com.mybatisflex.codegen.Generator
 */
@Accessors(chain = true)
@Getter
@Setter
@AllArgsConstructor
@Slf4j
public class MyCodegenEngine {
    public static final Marker marker = MarkerFactory.getMarker("MyFlexGenerator");
    protected DataSource dataSource;
    protected GlobalConfig globalConfig;

    public HashBasedTable<String, String, GenResult> generate() {
        HashBasedTable<String, String, GenResult> hashBasedTable = HashBasedTable.create();
        try {
            List<Table> tables = TableUtils.buildTables(dataSource, globalConfig);
            if (tables.isEmpty()) {
                System.err.printf("table %s not found.%n", globalConfig.getGenerateTables());
                return null;
            } else {
                System.out.printf("find tables: %s%n", tables.stream().map(Table::getName).collect(Collectors.toSet()));
            }

            for (Table table : tables) {
                for (Object config : globalConfig.getCustomConfig().values()) {
                    if (config instanceof MyCustomConfig myCustomConfig) {
                        IFileGenerator generator = myCustomConfig.getGenerator();
                        GenResult genResult = generator.generate(table, globalConfig);
                        hashBasedTable.put(myCustomConfig.getCode(), table.getName(), genResult);
                    }
                }

            }

            System.out.println("Code is generated successfully.");
        } catch (Exception e) {
            log.error(marker, "generate", e);
        }
        return hashBasedTable;
    }
}
